<template>
  <div>
    <template v-if="loading">
      <div>加载中...</div>
    </template>
    <template v-else>
      <a-select placeholder="" aria-hidden="false" style="width: 318px" v-model:value="value" :options="items">
        <template #dropdownRender>
          <div>
            <div v-for="(item, index) in items" :key="item.id">
              <a-space style="padding: 4px 8px">
                <span v-if="editingIndex === index">
                  {{ index+1 }} -
                  <a-input
                    v-model:value="editingValue"
                    @blur="saveEdit(index)"
                    @keyup.enter="saveEdit(index)"
                    class="w-155px"
                  />
                </span>
                <span v-else>{{ index+1 }} - {{ item.tel }}</span>
                <a-button
                  size="small"
                  type="link"
                  @click="startEdit(index)"
                  v-if="editingIndex !== index"
                >
                  <EditOutlined /> 编辑
                </a-button>
                <a-button
                  size="small"
                  type="link"
                  @click="handleDeleteConfirm(index)"
                >
                  <DeleteOutlined /> 删除
                </a-button>
              </a-space>
            </div>
            <a-divider style="margin: 4px 0" />
            <a-space style="padding: 4px 8px">
              <a-input ref="inputRef" v-model:value="name" placeholder="请输入电话号码" />
              <a-button type="text" @click="addItem">
                <template #icon>
                  <PlusOutlined />
                </template>
                添加
              </a-button>
            </a-space>
          </div>
        </template>
      </a-select>
    </template>
  </div>
</template>
<script lang="ts" setup>
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { customerTelAdd, customerTelEdit, customerTelDel, list } from "/@/views/full/customer/customer.tel";
import { ref, onMounted, nextTick, watchEffect, watch } from 'vue';
import { Modal } from 'ant-design-vue';
import { useMessage } from "/@/hooks/web/useMessage";
const { createMessage: $message } = useMessage();
// 定义 props
const props = defineProps({
  parentId: {
    type: String,
    default: ''
  },
  customerId: {
    type: String,
    default: ''
  },
  customerType: {
    type: String,
    default: ''
  },
  options: {
    type: Array,
    default: () => []
  },
  showOptionList: {
    type: Boolean,
    default: false
  },
  listTitle: {
    type: String,
    default: 'My Option List'
  },
  selectStyle: {
    type: [String, Object],
    default: 'width: 300px'
  }
});

// 声明 emits
const emit = defineEmits(['updateLxdh']);

const items = ref([
  // { id: '1', tel: '1234567890' },
  // { id: '2', tel: '0987654321' }
]);
const value = ref();
const inputRef = ref();
const name = ref();
const isEditing = ref(false);
const modalValue = ref('');
const editingIndex = ref(-1);
const editingValue = ref('');

// 添加加载状态
const loading = ref(true);
// 手机号校验正则
const phoneRegex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

// 从后台获取数据
const fetchItems = async () => {
  try {
    if (!props.customerId && props.customerType != '2') {
      items.value = [];
      value.value = "";
      loading.value = false;
      return;
    }
    loading.value = true;
    // 使用 props 中的 customerId
    const response = await list({ customerId: props.customerId });
    if (response.code === 200) {
      let result  = response.result.map((item) => {
        return { id: item.id, tel: item.tel };
      });
      if (result && result.length > 0) {
        items.value = result; // 假设返回的数据格式为包含编号和电话的数组
        console.log('获取数据成功:', items.value);
        // 触发自定义事件，传递数据个数
      } else {
        items.value = [];
        value.value = "";
        loading.value = false;
      }
    } else {
      items.value = [];
      value.value = "";
      loading.value = false;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
    // 使用 nextTick 确保 DOM 更新
    nextTick(() => {
      console.log('数据更新完成，DOM 已更新');
    });
  }
};

// 使用 watch 监听 props.customerId 和 props.parentId
watch([() => props.customerId, () => props.parentId], ([newCustomerId, newParentId], [oldCustomerId, oldParentId]) => {
  console.info('fetchItems 发生变化: customerId:', newCustomerId, 'parentId:', newParentId)
  if (newCustomerId !== oldCustomerId || newParentId !== oldParentId) { // 仅在 customerId 或 parentId 变化时执行
    if (!!newCustomerId) {
      fetchItems();
    } else {
      items.value = [];
      value.value = "";
      loading.value = false;
    }
  }
}, { deep: true });

// 使用 watch 替代 watchEffect 并添加 deep 选项
watch(() => items.value, (newItems) => {
  let length = newItems.length;
  console.info('items 发生变化:', newItems, length)
  if (length == 1) {
    value.value = newItems[0].tel;
  } else if (length > 1) {
    value.value = '录有' + length + '个号码';
  } else {
    value.value = '';
  }
  emit('updateLxdh', value.value);
  console.log('items 发生变化:', length);
}, { deep: true });

const addItem = async (e) => {
  e.preventDefault();
  const newPhone = name.value;
  if (!newPhone) {
    console.error('请输入电话号码');
    return;
  }
  // 手机号校验
  if (!phoneRegex.test(newPhone)) {
    $message.error('无效的手机号码');
    return;
  }

  if (items.value.some(item => item.tel === newPhone)) {
    $message.error('电话号码已存在');
    return;
  }

  if (!props.customerId) {
    if (items.value.length == 1) {
      $message.error('新增联系人时第一次只需添加一个号码！');
      return;
    }
    // customerId 为空，仅添加到本地列表并触发自定义事件
    const newItem = { id: Date.now().toString(), tel: newPhone };
    items.value.push(newItem);
    name.value = '';
    setTimeout(() => {
      inputRef.value?.focus();
    }, 0);
    // 触发自定义事件，传递临时电话号码列表
    emit('updateLxdh', newPhone);
    return;
  }

  try {
    const params = { customerId: props.customerId, tel: newPhone }
    const response = await customerTelAdd(params);
    if (response.success) { // 假设接口返回 success 字段表示成功
      const newItem = { id: response.result, tel: newPhone };
      items.value.push(newItem);
      name.value = '';
      setTimeout(() => {
        inputRef.value?.focus();
      }, 0);
    } else {
      $message.error(response.message);
    }
  } catch (error) {
    console.error('添加选项失败:', error);
  }
};

const startEdit = async (idx) => {
  try {
    //await axios.post('/api/start-edit', { index: idx, originalValue: items.value[idx] });
    editingIndex.value = idx;
    editingValue.value = items.value[idx].tel;
  } catch (error) {
    console.error('开始编辑失败:', error);
  }
};

const saveEdit = async (idx) => {
  if (editingValue.value.trim()) {
    try {
      const response = await customerTelEdit({
        id: items.value[idx].id,
        customerId: props.customerId,
        tel: editingValue.value.trim(),
      });
      if (response.code === 200) {
        items.value[idx].tel = editingValue.value.trim();
      }
    } catch (error) {
      console.error('保存编辑失败:', error);
    }
  }
  editingIndex.value = -1;
  editingValue.value = '';
};


// 处理删除确认对话框
const handleDeleteConfirm = (idx) => {
  Modal.confirm({
    title: '确认',
    content: '确定要删除这个选项吗？',
    onOk: () => deleteItem(idx),
    onCancel: () => console.log('取消'),
  });
};

const deleteItem = async (idx) => {
  try {
   await customerTelDel({ id: items.value[idx].id }).then((res) => {
    if (res.success) {
      items.value.splice(idx, 1);
      $message.success(res.message);
    } else {
      $message.error(res.message)
    }
  });
  } catch (error) {
    console.error('删除选项失败:', error);
  }
};

</script>